/**
 * axios promise 封装
 */
import axios from 'axios';
import qs from 'qs'
import i18n from "../lang/index.js"
import { Toast, Notify } from 'vant';

// axios.defaults.baseURL = "http://i.itpk.cn"

axios.interceptors.request.use(config => {
    return config
})

axios.interceptors.response.use(response => {
    return response
})

function request(url, data = {}, method, headers, isLoading = false) {
    isLoading && Toast.loading({ message: i18n.t('loading'), overlay: true })
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method: method,
            headers: {
                "Content-Type": headers && headers["Content-Type"] || "application/json"
            },
            data: method == "POST" ? qs.stringify(data) : data
        }).then(res => {
            resolve(res.data)
        }).catch(res => {
            console.log(res)
            Notify({ type: 'danger', message: '' + res });
            reject(res)
        }).finally(() => {
            isLoading && Toast.clear();
        })
    })
}

function requestAll(arr = [], isLoading = true) {
    isLoading && Toast.loading({ message: i18n.t('loading'), overlay: true });
    return Promise.all(arr).finally(() => {
        isLoading && Toast.clear();
    })
}

function get(url, data) {
    return request(url, data, "GET");
}

function post(url, data) {
    return request(url, data, "POST", { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" });
}
export {
    request,
    requestAll,
    post,
    get
}